﻿using System.Collections.ObjectModel;
using System.Collections.Specialized;
using EventLogAnalyzer.Model;

namespace EventLogAnalyzer.ViewModel
{
    public class LogFileViewModel : ViewModelBase
    {
        private readonly LogFile _model;
        public event ShowLogDetailsEventHandler ShowLogDetailsRequest;

        public LogFileViewModel(LogFile model)
        {
            Logs = new ObservableCollection<EventLogViewModel>();
            _model = model;
            _model.PropertyChanged += _model_PropertyChanged;
            _model.Logs.CollectionChanged += Logs_CollectionChanged;
        }

        void Logs_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if(e.Action == NotifyCollectionChangedAction.Add)
            {
                var newItem = (EventLog)e.NewItems[0];
                var eventLogViewModel = new EventLogViewModel(newItem);
                eventLogViewModel.ShowLogDetailsRequest += eventLogViewModel_ShowLogDetailsRequest;
                Logs.Add(eventLogViewModel);
            }
        }

        void eventLogViewModel_ShowLogDetailsRequest(object sender, ShowLogDetailsEventHandlerArgs args)
        {
            if (ShowLogDetailsRequest != null)
                ShowLogDetailsRequest(this, args);
        }

        void _model_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (IsValidProperty(e.PropertyName))
            {
                OnPropertyChanged(e.PropertyName);
            }
        }

        public string FileName
        {
            get { return _model.FileName.Substring(_model.FileName.LastIndexOf("\\")+1); }
        }


        public ObservableCollection<EventLogViewModel> Logs { get; set; }

        public int VisibleLogsCount { get; set; }
    }
}